package com.photoeditor.demo.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.support.annotation.DrawableRes;
import android.util.AttributeSet;

import com.common.base.utils.DebugUtil;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;


/**
 * Created by qinjinwen on 2016-12-28.
 * 圆角ImageView
 */

public class RoundImageView extends android.support.v7.widget.AppCompatImageView {

    private RectF mRoundRect;

    private Paint mPaint;

    private Matrix mMatrix;

    private float mRadius;//圆角半径

    private boolean mTopLeftRoundOnly;//只要左上角圆角
    private boolean mTopRightRoundOnly;//只要右上角圆角

    //用于调节哪个角不需要圆角，不合适有透明度的图片
    private boolean mBottomRightNotRound;
    private boolean mBottomLeftNotRound;
    private boolean mTopLeftNotRound;
    private boolean mTopRightNotRound;
    private boolean mIsCircle;//圆形图片
    private int mDefaultImageResource;
    private boolean mNeedCenterCrop;


    public RoundImageView(Context context) {
        this(context, null);
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundImageView);
        mBottomRightNotRound = typedArray.getBoolean(R.styleable.RoundImageView_lockBottomRightNotRound, false);
        mBottomLeftNotRound = typedArray.getBoolean(R.styleable.RoundImageView_lockBottomLeftNotRound, false);
        mTopLeftNotRound = typedArray.getBoolean(R.styleable.RoundImageView_lockTopLeftNotRound, false);
        mTopRightNotRound = typedArray.getBoolean(R.styleable.RoundImageView_lockTopRightNotRound, false);
        mTopLeftRoundOnly = typedArray.getBoolean(R.styleable.RoundImageView_lockTopLeftRoundOnly, false);
        mTopRightRoundOnly = typedArray.getBoolean(R.styleable.RoundImageView_lockTopRightRoundOnly, false);
        mIsCircle = typedArray.getBoolean(R.styleable.RoundImageView_lockIsCircle, false);
        mRadius = typedArray.getDimension(R.styleable.RoundImageView_lockRoundRadius, mRadius);
        mNeedCenterCrop = typedArray.getBoolean(R.styleable.RoundImageView_centerCrop, false);
        typedArray.recycle();
        mMatrix = new Matrix();
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setAntiAlias(true);

        if (mRadius == 0) {
            mRadius = DeviceUtils.dip2px(getContext(), 7);
        }
    }

    /**
     * 如果需要设置.9图作为默认背景，需要调用这个接口
     * setBackground无法圆角
     *
     * @param resid
     */
    public void setDefaultImageResource(@DrawableRes int resid) {
        mDefaultImageResource = resid;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        try {
            Drawable drawable = getDrawable();
            if (drawable == null && mDefaultImageResource != 0) {
                drawable = getContext().getResources().getDrawable(mDefaultImageResource);
            }
            if (drawable == null) {
                return;
            }
            setUpShader(drawable);
            if (mIsCircle) {
                canvas.drawCircle(getWidth() / 2, getHeight() / 2, getWidth() / 2 - 4, mPaint);
                return;
            }
            if (mTopLeftRoundOnly) {
                mRoundRect.bottom = mRoundRect.bottom + 20;
                mRoundRect.right = mRoundRect.right + 20;
            }
            if (mTopRightRoundOnly) {
                mRoundRect.bottom = mRoundRect.bottom + 20;
                mRoundRect.left = mRoundRect.left - 20;
            }
            canvas.drawRoundRect(mRoundRect, mRadius, mRadius, mPaint);
            if (mTopLeftNotRound) {
                canvas.drawRect(0, 0, mRadius, mRadius, mPaint);
            }
            if (mTopRightNotRound) {
                canvas.drawRect(getWidth() - mRadius, 0, getWidth(), mRadius, mPaint);
            }
            if (mBottomLeftNotRound) {
                canvas.drawRect(0, getHeight() - mRadius, mRadius, getHeight(), mPaint);
            }
            if (mBottomRightNotRound) {
                canvas.drawRect(getWidth() - mRadius, getHeight() - mRadius, getWidth(), getHeight(), mPaint);
            }
        } catch (Exception e) {
            if (DebugUtil.isDebuggable()) e.printStackTrace();
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mRoundRect = new RectF(0, 0, getWidth(), getHeight());
    }

    /**
     * drawable转bitmap
     */
    private Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bd = (BitmapDrawable) drawable;
            return bd.getBitmap();
        }
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();
        if (drawable instanceof NinePatchDrawable && getWidth() != 0 && getHeight() != 0) {
            w = getWidth();
            h = getHeight();
        }

        Bitmap bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 初始化BitmapShader
     */
    private void setUpShader(Drawable drawable) {
        if (drawable == null) {
            return;
        }
        Bitmap bmp = drawableToBitmap(drawable);
        if (mNeedCenterCrop) {
            bmp = resizeBitmapByCenterCrop(bmp, getWidth(), getHeight());
        }
        // 将bmp作为着色器，就是在指定区域内绘制bmp
        BitmapShader mBitmapShader = new BitmapShader(bmp, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
        // 如果图片的宽或者高与view的宽高不匹配，计算出需要缩放的比例；缩放后的图片的宽高，一定要大于我们view的宽高；所以我们这里取大值；
        // float scale = Math.max(getWidth() * 1.0f / bmp.getWidth(), getHeight() * 1.0f / bmp.getHeight());
        // shader的变换矩阵，我们这里主要用于放大或者缩小
        mMatrix.setScale(getWidth() * 1.0f / bmp.getWidth(), getHeight() * 1.0f / bmp.getHeight());
        // 设置变换矩阵
        mBitmapShader.setLocalMatrix(mMatrix);
        // 设置shader
        mPaint.setShader(mBitmapShader);
    }

    /**
     * 设置圆角半径
     */
    public void setRadius(int mRadius) {
        this.mRadius = mRadius;
    }

    public Bitmap resizeBitmapByCenterCrop(Bitmap src, int destWidth, int destHeight) {
        if (src == null || destWidth == 0 || destHeight == 0) {
            return null;
        }
        // 图片宽度
        int w = src.getWidth();
        // 图片高度
        int h = src.getHeight();
        // Imageview宽度
        int x = destWidth;
        // Imageview高度
        int y = destHeight;
        // 高宽比之差
        int temp = (y / x) - (h / w);
        /**
         * 判断高宽比例，如果目标高宽比例大于原图，则原图高度不变，宽度为(w1 = (h * x) / y)拉伸
         * 画布宽高(w1,h),在原图的((w - w1) / 2, 0)位置进行切割
         */

        if (temp > 0) {
            // 计算画布宽度
            int w1 = (h * x) / y;
            // 创建一个指定高宽的图片
            Bitmap newb = Bitmap.createBitmap(src, (w - w1) / 2, 0, w1, h);
            //原图回收
//            src.recycle();
            return newb;
        } else {
            /**
             * 如果目标高宽比小于原图，则原图宽度不变，高度为(h1 = (y * w) / x),
             * 画布宽高(w, h1), 原图切割点(0, (h - h1) / 2)
             */

            // 计算画布高度
            int h1 = (y * w) / x;
            // 创建一个指定高宽的图片
            Bitmap newb = Bitmap.createBitmap(src, 0, (h - h1) / 2, w, h1);
            //原图回收
//            src.recycle();
            return newb;
        }
    }
}
